/**
 * Created by yang.fan on 2017/11/17.
 */
import React from 'react';
import {Modal, Button,Row,Col,Cascader,Input,Form,message} from 'antd';
import styles  from './Track.less';
import { request } from '../../config/request'
const { Component } = React
import { cloneDeep } from 'lodash';
// 引入全局配置
import config from '../../config/config'
// 异步静态资源
import LoadAssets from 'load-assets'
import {QueryCondition} from 'widget/Grid/Grid'
import AdvanceSearch from '../CollapsiblePanels/AdvanceSearch'
import $ from 'jquery'
/*
 *
 * 地图组件
 *
 */
const FormItem = Form.Item;
const {Search} = Input
const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 19 },
};


export default class Track extends Component {
  // 构造函数
  constructor(props, context) {
    super(props, context);
    this.setMapRef = ref => {
      this.mapContainer = ref;
    };
    this.state = {
      queryList: cloneDeep(props.queryList),
      //根据经纬度获取逆地理位置
      address: this.props.address||'',

      //按钮的显示隐藏
      btnDiv: this.props.btnDiv || true,

      //开启关闭按钮
      visible: this.props.visible || false,

      //确定按钮
      cbk: ()=>{
        this.props.cbk(this.state.latAndLon, this.state.address);
      },

      //取消
      cancal: ()=>{
        this.props.cancal&&this.props.cancal()
      },

      // 地图实例
      map: null,

      // 图标实例
      marker: null,

      //经纬度 默认显示北京首都的经纬度
      latAndLon: this.props.latAndLon || [113.437218, 23.103965],

      //是否开启地图的点击功能
      clickRes: this.props.clickRes || true,
      //省市配置
      options:this.props.options,
      //选择的地址
      selectAddress:'',
      mapList: [],
      mapListShow: false
    }

  }

  // 加载静态资源及地图
  loadAssetsAndMap(key){
    let THIS = this
    // 加载地图所需静态资源
    // let assetsArray = [
    //   'https://cache.amap.com/lbs/static/main1119.css',
    //   'https://cache.amap.com/lbs/static/es5.min.js',
    //   'https://webapi.amap.com/maps?v=1.4.10&key=' +'7e61745f0e479ccedbcc70071ec3f690'
    // ]
    let assetsArray = [
      'https://api.map.baidu.com/library/TextIconOverlay/1.2/src/TextIconOverlay_min.js',
      'https://api.map.baidu.com/library/MarkerClusterer/1.2/src/MarkerClusterer_min.js',
      `https://api.map.baidu.com/api?v=3.0&ak=ORYNu4GTZHUUg8uT4rXuzfDMxQNvGGY1&callback=MapLoadSuccess`
    ]
    // 加载静态资源
    new LoadAssets(assetsArray, function(){
      // DOM加载完成之后，再加载地图
      if(THIS.props.latAndLon.length == 0||!THIS.props.latAndLon[0]){
        THIS.initMapfrist()
      }else{
        THIS.initMap()
      }
      
    })
  }

  //弹窗的确定按钮
  handleOk(){
    //console.log('确定')
  }

  //弹窗的取消按钮
  handleCancel(){
    let THIS = this;
    this.setState({visible: false}, ()=>{
      THIS.state.cancal();
    });
  }

  initMapfrist(){
      let _this = this
      var map = new BMap.Map(this.mapContainer);
      var point = new BMap.Point(113.437218,23.103965); 
      map.centerAndZoom(point,12);
      map.setDefaultCursor('pointer');
      map.enableScrollWheelZoom();
      map.addControl(new BMap.OverviewMapControl({ isOpen: true, size: new BMap.Size(140, 110) }));
      map.addControl(new BMap.NavigationControl());
    	// 百度地图API功能
      var geolocation = new BMap.Geolocation();
      geolocation.getCurrentPosition(function(r){
        if(this.getStatus() == BMAP_STATUS_SUCCESS){
          var mk = new BMap.Marker(r.point);
          map.addOverlay(mk);
          map.panTo(r.point);
          _this.setState({latAndLon:[r.point.lng, r.point.lat]})
          _this.setState({address:r.address.province+r.address.city})
        }      
      },{enableHighAccuracy: true})

      //创建一个地址解析器的实例
      var geoc = new BMap.Geocoder();
      //为地图实例添加了一个鼠标单击的监听事件
      map.addEventListener("click",function(e){
          map.clearOverlays();
          //事件参数e中保存了鼠标单击时所对应的地理位置point
          var pt = e.point;
          var marker = new BMap.Marker(new BMap.Point(pt.lng, pt.lat));
          map.addOverlay(marker);
          //将鼠标单击时的坐标进行逆地址解析
          geoc.getLocation(pt,function(rs){//解析的结果是一个对象，且作为参数传入了回调函数中
              //该对象的属性中保存了解析后的结构化的地址信息
              let address =  rs.surroundingPois&&rs.surroundingPois.length?rs.address + rs.surroundingPois[0].title:rs.address
              _this.setState({address: address})
              _this.setState({latAndLon:[rs.point.lng, rs.point.lat]})
              _this.state.cbk([rs.point.lng, rs.point.lat],address);
          })
      });

  }
   
  // 加载地图实例
  initMap(){
    let THIS = this
    // 创建地图实例
    // 百度地图API功能
    var map = new BMap.Map(this.mapContainer);
    var point = new BMap.Point(THIS.state.latAndLon[0], THIS.state.latAndLon[1]); 
    map.centerAndZoom(point,18);
    map.setDefaultCursor('pointer');
    map.enableScrollWheelZoom();
    map.addControl(new BMap.OverviewMapControl({ isOpen: true, size: new BMap.Size(140, 110) }));
    map.addControl(new BMap.NavigationControl());
    map.clearOverlays();
    var marker = new BMap.Marker(point);
    map.addOverlay(marker);

    if(this.state.btnDiv){
       //创建一个地址解析器的实例
       var geoc = new BMap.Geocoder();
       //为地图实例添加了一个鼠标单击的监听事件
       map.addEventListener("click",function(e){
           map.clearOverlays();
           //事件参数e中保存了鼠标单击时所对应的地理位置point
           var pt = e.point;
           var marker = new BMap.Marker(new BMap.Point(pt.lng, pt.lat));
           map.addOverlay(marker);
           //将鼠标单击时的坐标进行逆地址解析
           geoc.getLocation(pt,function(rs){//解析的结果是一个对象，且作为参数传入了回调函数中
               //该对象的属性中保存了解析后的结构化的地址信息
               let address =  rs.surroundingPois&&rs.surroundingPois.length?rs.address + rs.surroundingPois[0].title:rs.address
               THIS.setState({address: address})
               THIS.setState({latAndLon:[rs.point.lng, rs.point.lat]})
               THIS.state.cbk([rs.point.lng, rs.point.lat],address);
           })
       });
    }

    // 放到状态机
    this.setState({map, marker})

  }
  // //地理编码
  getLatAddress(address){
    var _this =this
    var map = new BMap.Map(this.mapContainer);
    map.clearOverlays();
    // var point = new BMap.Point(payload.latAndLon[0],payload.latAndLon[1]);
    // map.centerAndZoom(point, 18);
    // map.addOverlay(new BMap.Marker(point, {title: address}))

    // 百度地图API功能
    let options = {
      onSearchComplete: function(results){
        // 判断状态是否正确
        if (local.getStatus() == BMAP_STATUS_SUCCESS){
          var s = [];
          for (var i = 0; i < results.getCurrentNumPois(); i ++){
            let obj = {
              title:results.getPoi(i).title,
              address: results.getPoi(i).address,
              point: results.getPoi(i).point,
            }
            s.push(obj);
          }
            _this.setState({mapList:s})
            _this.setState({mapListShow:true})
        }
      }
    }
    let local = new BMap.LocalSearch(map,options);
    local.search(address)
  }
  updateAddress(el){
    this.setState({
      address:el.address?el.address:''
    })
    this.setState({latAndLon:[el.point.lng, el.point.lat]})
    this.setState({mapListShow:false})
    var map = new BMap.Map(this.mapContainer);
    var point = new BMap.Point(this.state.latAndLon[0], this.state.latAndLon[1]); 
    map.centerAndZoom(point,18);
    map.setDefaultCursor('pointer');
    map.enableScrollWheelZoom();
    map.addControl(new BMap.OverviewMapControl({ isOpen: true, size: new BMap.Size(140, 110) }));
    map.addControl(new BMap.NavigationControl());
    map.clearOverlays();
    var marker = new BMap.Marker(point);
    map.addOverlay(marker);
  }
  onChange(value,item) {
    let address = ''
    for(var i=0; i<item.length;i++){
      address+=item[i].label
    }
    this.setState({
      selectAddress:address
    })
    // this.getLatAddress(address)
  }
  render() {
    let THIS = this;
    let {selectAddress,latAndLon,mapList,mapListShow} =this.state;
    return (
      <div className={styles.map}>
        <Modal
          visible={THIS.state.visible}
          title={'地图'}
          onOk={this.handleOk}
          onCancel={this.handleCancel.bind(THIS)}
          width={1000}
          footer={null}
        >
          <div className="public_listMain">
            <Row>
              <Col span={7}>
                <FormItem {...formItemLayout}
                label="省市">
                <Cascader placeholder="请选择" options={THIS.state.options} onChange={this.onChange.bind(this)} />
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem {...formItemLayout}>
                <Search
                  placeholder="请输入地址"
                  onSearch={(value) => {
                    if(selectAddress.length>0){
                      let address = selectAddress + value
                      return this.getLatAddress(address)
                    }else{
                      return this.getLatAddress(value)
                    }
                  }}
                  enterButton
                />
                </FormItem>
                <div style={{display:mapListShow?'block':'none',position: 'absolute',left: '0',background: '#fff',zIndex:100,width:'73%',padding:'10px',top:'40px',boxShadow:'0 0 2px #aaa',maxHeight:'238px',overflowY:'scroll'}}>
                      {mapList == undefined ?null:mapList.map((el,inx)=>{
                        return (
                          <div key={inx} onClick={(e) => { this.updateAddress(el) }} style={{paddingBottom:'10px',borderBottom:'1px solid #eee',cursor:'pointer'}} >
                            <div>{el.title}</div>
                            <div>{el.address}</div>
                          </div>
                        )
                      })}
                </div>
              </Col>
              <Col span={5}>
                <span>
                规则遵循：国家、省份、城市、区县、城镇、乡村、街道、门牌号码、屋邨、大厦，如：北京市朝阳区阜通东大街6号。
                </span>
              </Col>
            </Row>
          </div>
          <div className={styles.mapExp}>请在地图中点击定位点至您的门店所在位置，并点击“确认”完成设置。</div>
          <div className={styles.mapCoo}>
            <span>你当前选取的位置为：</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            {THIS.state.address}&nbsp;&nbsp;&nbsp;
            ( 经度：{latAndLon[0]?latAndLon[0]:0}&nbsp;&nbsp;&nbsp;
            纬度：{latAndLon[1]?latAndLon[1]:0} )
          </div>
          <div className={styles.aMapInst} ref={this.setMapRef}></div>
          {
            this.state.btnDiv ? <div className={styles.mapBtn}>
              <Button
                onClick={()=>{
                  this.handleCancel();
                  THIS.state.cancal();
                }}>取消</Button>&nbsp;&nbsp;&nbsp;
              <Button
                type="primary"
                onClick={()=>{
                  this.handleCancel();
                  THIS.state.cancal();
                  THIS.state.cbk();
                }}>确定</Button>
            </div> : ''
          }

        </Modal>
      </div>
    )
  }

  //准备：即将被重新渲染，状态未变化
  componentWillUpdate(nextProps, nextState) {}

  //完成：正在被重新渲染，状态已变化
  componentDidUpdate(prevProps, prevState) {
  }

  // 已加载组件，收到新属性时调用
  componentWillReceiveProps(nextProps) {
    //console.log('nextProps: ',nextProps)

    if(nextProps.visible){
      let arr = nextProps.latAndLon.length <= 0 || !nextProps.latAndLon[0]? [] : nextProps.latAndLon;
        this.setState({visible: nextProps.visible,latAndLon:arr, btnDiv: nextProps.btnDiv,options:nextProps.options},()=>{
          this.loadAssetsAndMap(config.mapCfg.webServkey)
        });
    }
  }

  // 插入真实 DOM
  componentDidMount() {
    let THIS = this;
    // 加载Web服务地图实例
   // THIS.loadAssetsAndMap(config.mapCfg.webServkey)
  }


}


